package com.hjj.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.entity.Product;
import com.hjj.springboot.entity.RecommendationDTO;
import com.hjj.springboot.util.UserBehaviorCalculator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class RecommendationService {

    private final UserBehaviorCalculator userBehaviorCalculator;

    @Autowired
    private IProductService productService;

    /**
     * 获取个性化推荐商品列表
     *
     * @param userId              用户ID
     * @param topN                返回推荐数量
     * @return 推荐商品列表（带推荐分数）
     */
    public List<RecommendationDTO> getPersonalizedRecommendations(String userId, int topN) {
        // 1. 获取用户偏好分数
        Map<Integer, Double> productScores = userBehaviorCalculator.calculateUserPreferences(userId);


        // 2. 排序并截取前N个商品ID
        List<Integer> candidateIds = productScores.entrySet().stream()
                .sorted(Map.Entry.<Integer, Double>comparingByValue().reversed())
                .limit(topN)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        // 3. 获取商品详细信息
        List<Product> productList = productService.list(new QueryWrapper<Product>().in("id", candidateIds));

        // 4. 构建带推荐分数的DTO列表
        return productList.stream()
                .map(product -> new RecommendationDTO(
                        product,
                        productScores.get(product.getId())
                ))
                .sorted(Comparator.comparingDouble(RecommendationDTO::getRecommendScore).reversed())
                .collect(Collectors.toList());
    }
}
